package com.golddaymicromall.activity.tickert;

import com.golddaymicromall.util.RopUtils;
import com.golddaymicromall.util.ServerConfig;
import com.google.common.collect.Maps;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.convert.StringConvert;
import com.lzy.okrx.RxAdapter;

import java.util.Map;

import rx.android.schedulers.AndroidSchedulers;
import rx.subscriptions.CompositeSubscription;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Created by 王立强 on 2016/10/19.
 */

public class TicketPresenter implements TicketContract.Presenter {

    private TicketContract.View mView;

    private CompositeSubscription compositeSubscription;

    public TicketPresenter(TicketContract.View view){
        compositeSubscription = new CompositeSubscription();
        mView = checkNotNull(view,"View is not null");
        mView.setPresenter(this);
    }


    @Override
    public void saveTicketNo(String customerId, String ticketNo) {
        Map<String,String> form = Maps.newHashMap();
        form.put("method", "rop.shop.ticket");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("customerid", customerId);
        form.put("ticket", ticketNo);
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);

        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .doOnSubscribe(() -> {
                    mView.showLoading();
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s -> {
                    mView.dismissLoading();
                    mView.showTicketState(s);
                },throwable -> {
                    mView.dismissLoading();
                    mView.showError();
                    throwable.printStackTrace();
                });
    }

    @Override
    public void subscribe() {

    }

    @Override
    public void unsubscribe() {
        compositeSubscription.clear();
    }
}
